package com.lancoo.znbkxx.teacher.ui.activity

import android.content.Context
import android.content.Intent
import android.util.Log
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import com.lancoo.cpbase.authentication.base.*
import com.lancoo.znbkxx.teacher.Ext.Companion.BASE_ADDRESS
import com.lancoo.znbkxx.teacher.Ext.Companion.KEY
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.MyToast
import com.lancoo.znbkxx.teacher.base.BaseVMActivity
import com.lancoo.znbkxx.teacher.databinding.ActivityMainBinding
import com.lancoo.znbkxx.teacher.help.adapter.ZnbkPagerAdapter
import com.lancoo.znbkxx.teacher.ui.fragment.*
import com.lancoo.znbkxx.teacher.ui.fragment.cognitiveAssessment.CognitiveAssessmentFragment
import com.lancoo.znbkxx.teacher.utils.LancooUtils
import com.lancoo.znbkxx.teacher.utils.MkUtils
import com.lancoo.znbkxx.teacher.viewmodel.UserInfoViewModel
import com.tencent.bugly.beta.Beta
import com.tencent.bugly.beta.UpgradeInfo
import com.tencent.bugly.beta.ui.UILifecycleListener
import com.tencent.mmkv.MMKV
import com.tt.LancooSkEgnManager
import java.util.*

/**
 * @author : Admin
 * @date   : 2019/7/29 9:46
 * @desc   :
 */
class MainActivity : BaseVMActivity<UserInfoViewModel, ActivityMainBinding>() {
    private lateinit var mOperate: LoginOperate
    private var isExit = false

    override fun setLayoutID(): Int {
        return R.layout.activity_main
    }


    override fun providerVMClass(): Class<UserInfoViewModel>? {
        return UserInfoViewModel::class.java
    }

    override fun initView() {
//        setLoginSuccessData()
        fullScreen(true)
        initLoginOperate()
        initViewPager()
        initUpgrade()
        LancooSkEgnManager.getInstance(this).initSkegn(this, null)
    }

    /*初始化viewpager*/
    private fun initViewPager() {
        binding.vp.offscreenPageLimit = 3
        val mFragmentList = ArrayList<Fragment>()
        val aiPreparationFragment = AIPreparationFragment()
        val commentsFragment = CommentsFragment.newInstance(getString(R.string.title_problemcounseling))
        val cognitiveDiagnosisFragment = CognitiveDiagnosisFragment.newInstance(getString(R.string.title_analysis))
//        val cognitiveDiagnosisFragment = CognitiveAssessmentFragment.newInstance(getString(R.string.title_analysis))
        val personalCenterFragment = PersonalCenterFragment.newInstance(getString(R.string.title_personalcenter))
        mFragmentList.add(aiPreparationFragment)
        mFragmentList.add(commentsFragment)
        mFragmentList.add(cognitiveDiagnosisFragment)
        mFragmentList.add(personalCenterFragment)
        val fragmentManager = supportFragmentManager
        val transaction = fragmentManager.beginTransaction()
        transaction.add(aiPreparationFragment, "f0")
        transaction.add(commentsFragment, "f1")
        transaction.add(cognitiveDiagnosisFragment, "f2")
        transaction.add(personalCenterFragment, "f3")
        binding.vp.adapter = ZnbkPagerAdapter(supportFragmentManager, mFragmentList)
        binding.alphaIndicator.setViewPager(binding.vp)
        binding.alphaIndicator.setOnTabChangedListner {
            when (it) {
                0 -> fullScreen(true)
                else -> fullScreen(false)
            }
        }
    }


    private fun initLoginOperate() {
        mOperate = LoginOperate(this)
        //用户令牌失效回调接口
        TokenManager.getInstance().addTokenListener(tokenListener)
        //用户信息更新回调接口
        TokenManager.getInstance().setInfoListener(infoListener)
    }

    /*身份认证监听、用户信息监听*/
    private
    val tokenListener = TokenListener { flag ->
        if (flag == 0) {// 用户失效
            runOnUiThread {
                mOperate.openLoginDialog(
                        { setLoginSuccessData() },
                        false,
                        false,
                        { this.finish() })
            }
        } else if (flag == 1) {// 其他应用退出导致失效
            //当其他app进行登录操作时将回调tokenInvalid方法，且flag值为1
            runOnUiThread { this.finish() }
        }
    }

    /*用户信息更新回调*/
    private
    val infoListener = { runOnUiThread { setLoginSuccessData() } }

    private fun setLoginSuccessData() {
        val mAddress = AddressOperater(this)
        BASE_ADDRESS = mAddress.baseAddress
        MMKV.defaultMMKV()?.encode("BASE_ADDRESS", BASE_ADDRESS)
        KEY = LancooUtils.getBase64StuID(CurrentUser.UserID)
        MkUtils.encode("KEY", KEY)
        viewModel.getSystemConfigInfo(null,
                null,
                CurrentUser.Token,
                "C",
                CurrentUser.UserID
        )
    }

    override fun startObserve() {
        viewModel.baseInfo.observe(this, Observer {
            initViewPager()
        })
    }

    override fun onBackPressed() {
        exitBy2Click()
    }

    /**
     * 双击退出函数
     */
    private fun exitBy2Click() {
        val tExit: Timer?
        if (!isExit) {
            isExit = true // 准备退出
//            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show()
            MyToast.showToast("再按一次退出程序")
            tExit = Timer()
            tExit.schedule(object : TimerTask() {
                override fun run() {
                    isExit = false // 取消退出
                }
            }, 2000) // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务

        } else {
            finish()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 101 && resultCode == 2 && data != null) {
            val photourl = data.getStringExtra("photopath")
            CurrentUser.PhotoPath = photourl
            //更新头像
            Log.e("更新头像", "=========成功====111==========")
            //            setAvatar();
//            val mFragment = fmtList[4] as PersonalCenterFragment
//            mFragment.resultRefreshHeadImage()

        } else {
            Log.e("更新头像", "=========失败======111========$resultCode")
        }
    }

    private fun initUpgrade() {
        Beta.upgradeDialogLifecycleListener = object : UILifecycleListener<UpgradeInfo?> {
            override fun onCreate(context: Context, view: View, upgradeInfo: UpgradeInfo?) {
                Log.d("shishisaonian", "oncreate")
            }

            override fun onStart(context: Context, view: View, upgradeInfo: UpgradeInfo?) {
                Log.d("shishisaonian", "onStart")

            }

            override fun onResume(context: Context, view: View, upgradeInfo: UpgradeInfo?) {
                Log.d("shishisaonian", "onResume")

            }

            override fun onPause(context: Context, view: View, upgradeInfo: UpgradeInfo?) {
                Log.d("shishisaonian", "onPause")

            }

            override fun onStop(context: Context, view: View, upgradeInfo: UpgradeInfo?) {
                Log.d("shishisaonian", "onStop")

            }

            override fun onDestroy(context: Context, view: View, upgradeInfo: UpgradeInfo?) {
                Log.d("shishisaonian", "onDestroy")

            }
        }
    }
}